package com.tnl.app.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
//import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.tnl.app.dao.CityDAO;
import com.tnl.app.dao.DomainDAO;
import com.tnl.app.dao.SchDicDAO;
import com.tnl.app.dao.TbFileDAO;
import com.tnl.app.entity.City;
import com.tnl.app.entity.Domain;
import com.tnl.app.entity.SchJobPerson;
import com.tnl.app.entity.SchPerson;
import com.tnl.app.entity.TbFile;
import com.tnl.app.service.impl.SchPersonService;
import com.tnl.base.web.JsonController;

@Controller
@RequestMapping("/schPerson") 
public class SchPersonController extends JsonController{
	public static final String QNACCESS_KEY = "fc3vAVzCctz8YXwyyr6W3TBAiZKMHQknqY4ObUKL";
	 public static final String QNSECRET_KEY = "f_xZjBzq258akREeoZJeqbRDhISZV6nu8Tu4_mw1";
	 
	@Autowired
	private SchPersonService schPersonService;
	@Autowired
	private TbFileDAO tbFileDAO;
	@Autowired
	private SchDicDAO schDicDAO;
	@Autowired
	private CityDAO cityDAO;
	@Autowired
	private DomainDAO domainDAO;
	
//	@RequestMapping("/add")
//	public void addPerson(@RequestBody SchPerson schPerson,HttpServletResponse response) {
//		String id = UUID.randomUUID().toString().replace("-", "");
//		schPerson.setId(id);
//		schPersonService.insert(schPerson);
//		this.successJson(id, "success", response);
//	}
	
	@RequestMapping("/get/{id}")
	public void getPerson(@PathVariable("id") String id,HttpServletResponse response) {
		this.successJson(schPersonService.getById(id), "success", response);
	}
	
//	@RequestMapping("/update")
//	public void eidtPerson(@RequestBody SchPerson schPerson,HttpServletResponse response) {
//		schPersonService.update(schPerson);
//		this.successJson(schPerson.getId(), "success", response);
//	}
	
	
	@RequestMapping("/getByUnionid/{unionid}")
	public void getByUnionid(@PathVariable("unionid") String unionid,HttpServletResponse response) {
		SchPerson person = schPersonService.getByUnionid(unionid);
		if (person != null) {
			person.setSchoolName(schDicDAO.getName(person.getSchool(), "school"));
			person.setSpecialtyName(schDicDAO.getName(person.getSpecialty().toString(), "spec"));

			if (person.getExceptDomain() != null) {
				Domain domain = domainDAO.getById(Integer.valueOf(person.getExceptDomain()));
				person.setExceptDomainName(domain!=null?domain.getName():"");
			}
			
		}
		this.successJson(person == null ? null:person, "success", response);
	}
	
	@RequestMapping("/uploadFile")
	public void uploadFile(MultipartFile file,String id,
			HttpServletRequest servletRequest,HttpServletResponse response) {
		if(StringUtils.isBlank(id)) {
			this.errorJson(null, "请先填写个人信息", response);
		}
		 String documentId=null;
		 System.out.println(servletRequest.toString());
		 if(file!=null&&file.getSize()>0){
			String path = servletRequest.getSession().getServletContext().getRealPath("")+"upload/";
			String fileName = file.getOriginalFilename();
		    String suffix=fileName.substring(fileName.lastIndexOf(".")+1);
			FileOutputStream fos;
			documentId="doc-"+DateFormatUtils.format(new Date(), "yyyyMMddHHmmss")+String.format("%04d",new Random().nextInt(9999));
			String newFileName = documentId+"."+suffix;// 避免冲突
			String filePath=path+ newFileName;
			
			try {
				fos = FileUtils.openOutputStream(new File(filePath));
				IOUtils.copy(file.getInputStream(), fos);
				fos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch blocks
				e.printStackTrace();
			}
			//调用七牛云api，暂不封装 FileUtils.uploadFile(filePath, newFileName, "headoffer", Zone.zone0());
			try {
				Configuration cfg = new Configuration(Zone.zone0());
				UploadManager uploadManager = new UploadManager(cfg);
				Auth auth = Auth.create(QNACCESS_KEY, QNSECRET_KEY);
				String upToken = auth.uploadToken("headoffer");
				Response res = uploadManager.put(filePath, fileName, upToken);
				// 解析上传成功的结果
				DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
				System.out.println("七牛云上传response key:"+putRet.key);
				System.out.println("七牛云上传response hash:"+putRet.hash);
				if(true){
					TbFile tbFile=new TbFile();
					tbFile.setDocId(documentId);
					tbFile.setJobId(0);
					tbFile.setPersonId(0);
					tbFile.setStudentId(id);
					tbFile.setOriginal_name(fileName);
					tbFile.setNew_name(newFileName);
					tbFile.setFile_type(suffix);
					tbFile.setFile_path(filePath);
					tbFile.setRelative_path("https://tiaonali.com/"+newFileName);
					tbFile.setCreat_time(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
					tbFile.setUpdate_time(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
					tbFile.setCreate_by(id);
					tbFile.setUpdate_by(id);
					tbFileDAO.saveNEW(tbFile);
				}
			} catch(Exception e) {
				e.printStackTrace();
			}
			this.successJson(null, "success", response);
		 }
		 this.errorJson(null, "简历不能为空", response);
	}
	
	/**
	 * MultipartFile
	 */
	@RequestMapping("/uploadTest")
	@ResponseBody
	public void upload(HttpServletRequest request,
			@RequestParam String unionid,
			@RequestParam String fileName) {
		System.out.println("upload");
		System.out.println(unionid);
		System.out.println(fileName);
	}
	
	@RequestMapping("/hasSendEmail")
	public void hasSendEmail(String unionid,String jobId,HttpServletResponse response) {
		Boolean tag = false;
		SchJobPerson sjp = schPersonService.hasSendEmail(unionid,jobId);
		if (sjp!=null) {
//			Calendar c = Calendar.getInstance();
//			c.setTime(sjp.getCreateTime());
//			c.add(Calendar.DAY_OF_MONTH, 1);
//			if (c.getTimeInMillis() < System.currentTimeMillis()) {
				tag = true;
//			}
		}
		this.successJson(tag, "success", response);
	}
	
	@RequestMapping("/sendEmail")
	public void sendEmail(String unionid,String jobId,HttpServletResponse response) {
		this.successJson(schPersonService.addSendRecord(unionid,jobId), "success", response);
	}
	
	@RequestMapping("/addBase")
	public void addBase(SchPerson schPerson, HttpServletResponse response) {
		String id = UUID.randomUUID().toString().replace("-", "");
		schPerson.setId(id);
		schPersonService.addBase(schPerson);
		this.successJson(id, "success", response);
	}
	
	@RequestMapping("/updateBase")
	public void updateBase(SchPerson schPerson, HttpServletResponse response) {
		schPersonService.updateBase(schPerson);
		this.successJson(schPerson.getId(), "success", response);
	}
	
	@RequestMapping("/updateExcept")
	public void updateExcept(SchPerson schPerson, HttpServletResponse response) {
		System.out.println("schPerson param:"+schPerson.getExceptCityName1());
		schPersonService.updateExcept(schPerson);
		this.successJson(null, "success", response);
	}
}
